package com.caikun.service_management.controller;

import com.caikun.model.common.Result;
import com.caikun.model.entity.ServiceEntity;
import com.caikun.model.vo.PackageVO;
import com.caikun.service_management.service.ServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/service")
@Slf4j
@Tag(name = "服务管理")
public class ServiceController {

    @Autowired
    private ServiceService serviceService;

    @GetMapping("/list")
    public Result list(@RequestParam(name = "serviceName", required = false) String serviceName) {

        log.info("serviceName:{}", serviceName);
        List<ServiceEntity> serviceEntities = serviceService.listServices(serviceName);

        return Result.success(serviceEntities);
    }

    @PostMapping
    public Result add(@RequestBody ServiceEntity serviceEntity) {
        log.info("serviceEntity:{}", serviceEntity);
        serviceService.addService(serviceEntity);

        if(serviceEntity.getServiceId() == null) {
            return Result.fail("添加失败");
        }

        return Result.success(null);
    }

    @PutMapping("/{serviceId}")
    public Result update(@PathVariable Integer serviceId, @RequestBody ServiceEntity serviceEntity) {

        serviceEntity.setServiceId(serviceId);
        Boolean res = serviceService.updateService(serviceEntity);

        if(!res) {
            return Result.fail("更新失败");
        }

        return Result.success(null);
    }

    @DeleteMapping("/{serviceId}")
    public Result delete(@PathVariable Integer serviceId) {
        Boolean res = serviceService.deleteService(serviceId);

        if(!res) {
            return Result.fail("删除失败");
        }

        return Result.success(null);
    }

    @Operation(summary = "查询所有服务/套餐")
    @GetMapping("/queryAll")
    public Result queryAll(@RequestParam Integer serviceType) {

        log.info("开始处理查询，serviceType={}", serviceType);
        long start = System.currentTimeMillis();

        if(serviceType == 0) { // 单项服务列表
            log.info("开始查询单项服务");
            List<ServiceEntity> serviceEntities = serviceService.queryAllService();
            log.info("单项服务查询完成，耗时={}ms", System.currentTimeMillis() - start);
            return Result.success(serviceEntities);
        }
        if(serviceType == 1) { // 组合服务列表
            List<PackageVO> packageVOList = serviceService.queryAllPackageWithServices();
            log.info("组合服务查询完成 = {}", packageVOList);
            return Result.success(packageVOList);
        }

        return Result.fail(null);
    }
}
